package com.tanhua.dubbo.api.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.domain.db.QuestionUserLock;
import com.tanhua.dubbo.api.QuestionUserLockApi;
import com.tanhua.dubbo.mapper.QuestionUserLockMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class QuestionUserLockApiImpl implements QuestionUserLockApi {

    @Autowired
    private QuestionUserLockMapper questionUserLockMapper;


    @Override
    public void save(QuestionUserLock questionUserLock) {
        questionUserLockMapper.insert(questionUserLock);
    }

    @Override
    public List<QuestionUserLock> findByUserId(Long userId) {
        QueryWrapper<QuestionUserLock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<QuestionUserLock> questionUserLockList = questionUserLockMapper.selectList(queryWrapper);
        return questionUserLockList;
    }

    @Override
    public QuestionUserLock findByQuestionnaireId(Long questionnaireId, Long userId) {
        QueryWrapper<QuestionUserLock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("questionnaire_id", questionnaireId).eq("user_id", userId);
        QuestionUserLock questionUserLock = questionUserLockMapper.selectOne(queryWrapper);
        return questionUserLock;
    }

    @Override
    public void updateLock(Integer level, Long userId) {
        // 1. 先查询出是否下一等级是否有数据
        List<QuestionUserLock> questionUserLockList = findByLevel(level + 1, userId);
        // 2. 下一等级有表才更新状态
        QueryWrapper<QuestionUserLock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("level", level + 1);
        if(questionUserLockList != null && questionUserLockList.size() > 0) {
            for (QuestionUserLock questionUserLock : questionUserLockList) {
                // 判断是否处于倍锁住的状态，如果没有不做操作
                if(questionUserLock.getIsLock() == 1) {
                    questionUserLock.setIsLock(0);
                    questionUserLockMapper.update(questionUserLock, queryWrapper);
                }
            }
        }
    }

    @Override
    public List<QuestionUserLock> findByLevel(Integer level, Long userId) {
        QueryWrapper<QuestionUserLock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("level", level);
        List<QuestionUserLock> questionUserLockList = questionUserLockMapper.selectList(queryWrapper);
        return questionUserLockList;
    }
}
